package Stack;

import java.util.Stack;

class MyQueue {

    private Stack<Integer> stack1;
    private Stack<Integer> stack2;
    public MyQueue() {
        stack1 = new Stack<>();
        stack2 = new Stack<>();
    }

    public void push(int x) {
        stack1.push(x);
    }

    public int pop() {
        if(empty()) return -1;
        if(!stack2.empty()){
            return stack2.pop();
        }else{
            int size = stack1.size();
            for(int i = 0 ; i < size ; i++){
                int val = stack1.pop();
                stack2.push(val);
            }
            return stack2.pop();
        }
    }

    public int peek() {
        if(empty()) return -1;
        if(!stack1.empty() && stack2.empty() ){
            int val = 0;
            int size = stack1.size();
            for(int i = 0 ; i < size ; i++){
                val = stack1.pop();
                stack2.push(val);
            }
            return val;
        }else {
            return stack2.peek();
        }
    }

    public boolean empty() {
        return ( stack1.empty() && stack2.empty() );
    }
}

============================================================
//上面是第一遍写的,发现有些地方冗余可以优化,完成如下:
============================================================
class MyQueue {

    private Stack<Integer> stack1;
    private Stack<Integer> stack2;
    public MyQueue() {
        stack1 = new Stack<>();
        stack2 = new Stack<>();
    }
    
    public void push(int x) {
        stack1.push(x);
    }
    
    public int pop() {
        if(empty()) return -1;
        if(stack2.empty()){
            while(!stack1.empty()){
                stack2.push(stack1.pop());
            }
        }
        return stack2.pop();
    }
    
    public int peek() {
        if(empty()) return -1;
        if(stack2.empty()){
            while(!stack1.empty()){
                stack2.push(stack1.pop());
            }
        }
        return stack2.peek();
    }
    
    public boolean empty() {
        return ( stack1.empty() && stack2.empty() );
    }
}